# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                        di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of Promogest.

#    Promogest is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    Promogest is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with Promogest.  If not, see <http://www.gnu.org/licenses/>.

import urllib2
import urllib
import collections
import csv
import itertools
import base64
import hashlib
import datetime
import Environment
from web_lib.page import Page, expose, Response, change_schema
import json
from dao.Ente import Ente
import datetime
from lib.utils import prep2json, dateToString
from webEnv import *
from web_lib.webutils import leggiInSessione
import ckanapi

def _import_csv_create_(req, action=None):
    from dao.Categoria import Categoria
    from dao.CategoriaCampo import CategoriaCampo
    from dao.OpenData import OpenData
    from dao.EnteCategoria import EnteCategoria
    d = OpenData()
    categorie = Categoria().select(batchSize=None, orderBy="denominazione")
    enti = []
    if leggiInSessione(req, sezione="Main", chiave="schema"):
        enti = Ente().select(denominazione_breve=leggiInSessione(req, sezione="Main", chiave="schema"),orderBy="denominazione", batchSize=None)
    if not enti:
        enti = Ente().select(batchSize=None,orderBy="denominazione")
    #print "DDDD", d.__dict__
    pageData = {'file': "pg/addedit/ae_importcsvcreate",
                "dao": d,
                "categorie": categorie,
                "enti":enti
                }
    return Page(req).render(pageData)


def _import_csv_update_(req, action=None):
    from dao.CategoriaCampo import CategoriaCampo
    from dao.OpenData import OpenData
    from dao.Categoria import Categoria
    from dao.Ente import Ente
    url_red = "/pg/ac_Rilevazioni"
    idCategoria = int(req.form.get("id_categoria"))
    idEnte = int(req.form.get("id_ente"))
    categoria = Categoria().getRecord(id= int(req.form.get("id_categoria")))
    ente = Ente().getRecord(id= int(req.form.get("id_ente")))
    delimiter = str(req.form.get("separatore"))
    quotechar = str(req.form.get("delimitatore"))
    jumprow =   int(req.form.get("jumprow"))
    f = req.files["inputCSV"]
    #nome = f.filename()
    f.save("tpm")
    has = hashlib.sha224(str(f)).hexdigest()
    #has = hashlib.sha224(str(spamreader)).hexdigest()
    spamreader = csv.reader(open("tpm","rU"),delimiter=delimiter, quotechar=quotechar,dialect=csv.excel_tab)
    od = OpenData().select(hash_importazione = has, batchSize=None)
    if req.form.get("add") =="Cancella":
        for d in od:
            d.delete()
        return Page(req).redirect(url_red)
    for _ in itertools.repeat(None, jumprow):
        #try:
        spamreader.next()
        #except:
        #print " ERRORE NEL SALTO DELLA PRIMA RGA"
    tai = CategoriaCampo().select(id_categoria=idCategoria, batchSize=None)
    campi = [x.campo for x in tai]
    for row in spamreader:
        d = OpenData()
        d.id_categoria = idCategoria
        d.id_ente = idEnte
        d.hash_importazione = has
        d.data_inserimento = datetime.datetime.now()
        dd = {}
        for c in campi:
            if c.denominazione !="nullo":
                try:
                    dd[c.denominazione] = str(row[campi.index(c)]).decode('iso8859-1').encode('utf-8')
                except:
                    dd[c.denominazione] = str(row[campi.index(c)])
                dd["id_"+c.denominazione] = c.id
        dd["id_categoria"] = idCategoria
        dd["Categoria"] = categoria.denominazione
        dd["Ente"]= ente.denominazione
        d.objson = json.dumps([dd], ensure_ascii=False, encoding='utf8')
        has_record = hashlib.sha224(str(d.objson)).hexdigest()
        odd = OpenData().select(hash_record = has_record, batchSize=None)
        if not odd:
            d.hash_record = has_record
            Environment.session.add(d)
    Environment.session.commit()
    url_red = "/pg/ac_Rilevazioni"
    return Page(req).redirect(url_red)
